package XPath;

import org.dom4j.*;
import org.dom4j.io.SAXReader;
import org.junit.Test;

import java.util.List;

public class XPathDemo {
    @Test
    public void parse() throws Exception {
        SAXReader saxReader = new SAXReader();
        Document document=saxReader.read(XPathDemo.class.getResourceAsStream("/Contacts2.xml"));
        List<Node> nameNodes=document.selectNodes("/contactList/contact/name");
        for (Node nameNode : nameNodes) {
            Element element=(Element) nameNode;
            System.out.println(element.getTextTrim());
        }
    }

    //全文检索
    @Test
    public void parse2() throws Exception {
        SAXReader saxReader = new SAXReader();
        Document document=saxReader.read(XPathDemo.class.getResourceAsStream("/Contacts2.xml"));
        List<Node> nameNodes=document.selectNodes("//name");
        for (Node nameNode : nameNodes) {
            Element element=(Element) nameNode;
            System.out.println(element.getTextTrim());
        }
    }

    @Test
    public void parse3() throws Exception {
        SAXReader saxReader = new SAXReader();
        Document document=saxReader.read(XPathDemo.class.getResourceAsStream("/Contacts2.xml"));
        List<Node> nameNodes=document.selectNodes("//@id");
        for (Node nameNode : nameNodes) {
            Attribute attr= (Attribute) nameNode;
            System.out.println(attr.getName()+"=======>"+attr.getValue());
        }

        //查询name元素（包含id属性）
        //Node node=document.selectSingleNode("//name[@id=888]");
        Node node=document.selectSingleNode("//name[@id]");
        Element ele= (Element) node;
        System.out.println(ele.getTextTrim());
    }


}
